<?php

/**
 * Created by PhpStorm.
 * User: user
 * Date: 2017/11/30
 * Time: 16:39
 */
class ProductTaskAction extends Action
{
    //任务列表
    public function getList($search=null,$status=NULL,$start=0,$limit=10,$startTime = null,$endTime=null)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $userTask = M('module_user_task');
        Session::switchCustomer($customerId);
        $where["a.cId"] = array("eq", $customerId);
        if ($search) {
            $condition['a.taskName'] = array("like", "%$search%");
            $condition['c.nickname'] = array("like", "%$search%");
            $condition['_logic'] = 'or';
            $where["_complex"] = $condition;
        }
        if (!is_null($status)) {
            switch ($status) {
                case 1:
                    $where['a.status'] = array("eq", 2);
                    break;
                case 2:
                    $where['a.status'] = array("in", [0,1]);
                    break;
                case 3:
                    $where['a.status'] = array("eq",3);
                    break;
                case 4://孟慧添加于20180409 增加待审核状态筛选
                    $where['a.status'] = array("eq",4);
                    break;
            }
        }
        //孟慧添加于20180409 增加更新时间的起止筛选项
        if ($startTime != '' && $endTime != '') {
            $where['a.updateTime'] = array(array('egt', $startTime), array('elt', date('Y-m-d', strtotime("$endTime +1 day"))));
        } else if ($startTime != '') {
            $where["a.updateTime"] = array('egt', $startTime);
        } else if ($endTime != '') {
            $where["a.updateTime"] = array('elt', date('Y-m-d', strtotime("$endTime +1 day")));
        }
        $list = $userTask->alias("a")
            ->join("inner join wx_module_product_order b on a.oid=b.id")
            ->join("wx_" . $customerId . "_user_weixin_info c on a.uid = c.userId")
            ->where($where)
            ->field("a.id,c.nickname,c.headimgurl,b.serialNumber,a.progress,a.status,a.startTime,a.updateTime,a.configJson,a.taskName")
            ->order("a.updateTime desc")
            ->limit($start, $limit)
            ->select();
        if ($list) {
            foreach ($list as $key => $value) {
                $configJson = json_decode($value['configJson'], true);
                $allProgress = json_decode($configJson['progress'], true);
                $list[$key]['allProgress'] = count($allProgress);
            }
            $count = $userTask->alias("a")
                ->join("inner join wx_module_product_order b on a.oid=b.id")
                ->join("wx_" . $customerId . "_user_weixin_info c on a.uid = c.userId")
                ->where($where)
                ->count('a.id');
            Output::instance()->objArray($list, $count);
        } else {
            Output::instance()->resultCode();
        }
    }
    //任务统计
    public function taskStatictis($search=null,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $userTask = M('module_user_task');
        Session::switchCustomer($customerId);
        $where["cId"] = array("eq", $customerId);
        $search?$where["taskName"] = array("like", "%$search%"):"";
        $list = $userTask
            ->where($where)
            ->field("pid,taskName")
            ->order("updateTime desc")
            ->limit($start, $limit)
            ->group("pid")
            ->select();
        if($list){
            foreach($list as $key=>$value){
                $list[$key]['joinCount'] = $userTask->where("pid=".$value['pid'])->count("id");
                $list[$key]['finishCount'] = $userTask->where("status=2 and pid=".$value['pid'])->count("id");
            }
            $count = $userTask
                ->field("pid")
                ->where($where)
                ->group('pid')
                ->select();
            $count = count($count);
            Output::instance()->objArray($list,$count);
        }else{
            Output::instance()->resultCode();
        }
    }
    //任务下关卡统计
    public function progressStatictics($pid){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $taskModel = M("module_user_task");
        $progressModel = M('module_user_progress');
        Session::switchCustomer($customerId);
        $where['pid'] = array("eq",$pid);
        $where['cId'] = array("eq",$customerId);
        $taskConfig = $taskModel->where("pid=$pid")->getField("configJson");
        $taskConfig = json_decode($taskConfig,true);
        $progress = json_decode($taskConfig['progress'],true);
        foreach($progress as $key=>$value){
            $progress[$key]['id'] = $key+1;
            $progress[$key]['joinCount'] = $progressModel->where("pid=$pid and progressId=". $progress[$key]['id'])->count("id");
            $progress[$key]['finishCount'] = $progressModel->where("pid=$pid and progressId=". $progress[$key]['id']." and status=1")->count("id");
        }
        $count = count($progress);
        Output::instance()->objArray($progress,$count);
    }
    //任务下关卡列表
    public function progressList($taskId,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $taskModel = M("module_user_task");
        $progressModel = M('module_user_progress');
        Session::switchCustomer($customerId);
        $where['id'] = array("eq",$taskId);
        $where['cId'] = array("eq",$customerId);
        $taskConfig = $taskModel->where("id=$taskId")->getField("configJson");
        $taskConfig = json_decode($taskConfig,true);
        $progress = json_decode($taskConfig['progress'],true);
        foreach($progress as $key=>$value){
            $progress[$key]['id'] = $key+1;
            $progressInfo = $progressModel->where("taskId=$taskId and progressId=". $progress[$key]['id'])->find();
            if($progressInfo){
                $progress[$key]['taskId'] = $taskId;
                $progress[$key]['examineTime'] = $progressInfo['examineTime'];
                $progress[$key]['updateTime'] = $progressInfo['updateTime'];
                $progress[$key]['descript'] = $progressInfo['descript'];
                $progress[$key]['status'] = $progressInfo['status'];
            }else{
                unset($progress[$key]);
            }
        }
        $count = count($progress);
        $progress = array_slice($progress,$start,$limit);
        Output::instance()->objArray($progress,$count);
    }
    //关卡消息列表
    public function massgeList($taskId,$progressId){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $messageModel = M("module_task_massage");
        $progressModel = M("module_user_progress");
        Session::switchCustomer($customerId);
        $where['progressId'] = $progressId;
        $where['deleted'] = 0;
        $where['taskId'] = $taskId;
        $list = $messageModel->where($where)->field("id,content,type,createTime")->select();
        $progressInfo = $progressModel->where("taskId=$taskId and progressId=$progressId")->field("status,examineReason")->find();
        if($list){
            $data['list'] = $list;
            $data['status'] = $progressInfo['status'];
            $data['examineReason'] = $progressInfo['examineReason'];
            Output::instance()->object($data);
        }else{
            Output::instance()->resultCode();
        }
    }
    //关卡审核
    public function updateProgressStatus($taskId,$progressId,$status,$examineReason){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $taskModel = M("module_user_task");
        $progressModel = M("module_user_progress");
        $taskMessage = M("module_task_massage");
        Session::switchCustomer($customerId);
        $mallStore = M("module_mall_store");
        $proInfo = $progressModel->alias("a")
            ->join("inner join wx_".$customerId."_user b on a.uid=b.id")
            ->join("inner join wx_module_user_task c on a.taskId=c.id")
            ->where("a.progressId = $progressId and a.taskId=$taskId")->field("a.uid,a.taskId,a.wish,a.money,b.userName,c.taskName,a.status")->find();
        if ($proInfo['status'] == 1 ){
            $return['code'] = 1;
            $return['msg'] = '已经审核通过，无需再次审核';
            Output::instance()->object($return);
            return;
        }
        $where['progressId'] = array("eq",$progressId);
        $where['taskId'] = array("eq",$taskId);
        $data['status'] = $status;
        $data['examineReason'] = $examineReason;
        $data['examineTime'] = date("Y-m-d H:i:s");
        $result = $progressModel->where($where)->save($data);
        $url = WeixinApi::getDomainName();
        $tempUrl = $url['SERVER_HOST']. "call.html?customerId=" . $customerId .
            "&module=productTask&method=index&params=%7B%22id%22%3A$taskId,%22h%22%3A%22progressList%22%7D";
        $tempUrl = urlencode($tempUrl);
        if($status==1){
            $configJson = $taskModel->where("id=$taskId")->getField("configJson");
            $configJson = json_decode($configJson,true);
            $progress = json_decode($configJson['progress'],true);
            $taskData['progress'] = $progressId;
            if($progressId==count($progress)){
                $taskData['status'] = 2;
                $taskData['endTime'] = date("Y-m-d H:i:s");
                $taskData['updateTime'] = date("Y-m-d H:i:s");
            }else{//孟慧添加于20180409，用于审核通过后的状态改为进行中
                $taskData['status'] = 1;
            }
            $taskModel->where("id=$taskId")->save($taskData);
            $sendData['first'] = array('value'=> '您提交的任务审核通过','color'=>'#3f960b');
            $sendData['keyword1'] = array('value'=> $proInfo['taskName'],'color'=>'#173177');
            $sendData['keyword2'] = array('value'=> '审核通过','color'=>'#173177');
        }else{
            $sendData['first'] = array('value'=> '您提交的任务审核没有通过','color'=>'#f80712');
            $sendData['keyword1'] = array('value'=>  $proInfo['taskName'],'color'=>'#173177');
            $sendData['keyword2'] = array('value'=> '审核驳回','color'=>'#173177');

            //孟慧添加于20180409，用于审核后的状态改为进行中
            $taskData['status'] = 1;
            $taskModel->where("id=$taskId")->save($taskData);
        }
        if($result!==false){
            if($examineReason){
                $taskMessage_data['taskId'] = $taskId;
                $taskMessage_data['progressId'] = $progressId;
                $taskMessage_data['customerMassage'] = 1;
                $taskMessage_data['content'] = $examineReason;
                $taskMessage_data['type'] = 'text';
                $taskMessage_data['createTime'] = date("Y-m-d H:i:s");
                $taskMessage_data['updateTime'] = date("Y-m-d H:i:s");
                $taskMessage_result = $taskMessage->add($taskMessage_data);
                if(!$taskMessage_result){
                    Output::instance()->resultCode(code_sql_error);
                    return;
                }
            }
            if($status==1&&$proInfo['money']>0){
                $mallInfo = $mallStore->find();
                $setting = R("CUser/getMallSetting");
                WeixinApi::sendRedEnvelopeByOpenId(
                    $mallInfo["name"],
                    $proInfo['userName'],
                    $proInfo['money'],
                    $proInfo['wish'],
                    false,
                    $setting['payKey'],
                    $setting['mchId'],
                    $setting['appId'],
                    '',
                    1
                );
            }
            $sendData['keyword3'] = array('value'=> $examineReason,'color'=>'#173177');
            $sendData['remark'] = array('value'=>'点击进入任务' ,'color'=>'#0751f8');
            TemplateMessage::send( $proInfo['userName'],$customerId,'taskExamine',$tempUrl,$sendData);
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //发送消息
    public function sendMessage($taskId,$progressId,$examineReason=null,$picUrl=null){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $taskMessage = M("module_task_massage");
        Session::switchCustomer($customerId);
        if($examineReason){
            $data['taskId'] = $taskId;
            $data['progressId'] = $progressId;
            $data['customerMassage'] = 1;
            $data['content'] = $examineReason;
            $data['type'] = 'text';
            $data['createTime'] = date("Y-m-d H:i:s");
            $data['updateTime'] = date("Y-m-d H:i:s");
            $result = $taskMessage->add($data);
            if(!$result){
                Output::instance()->resultCode(code_sql_error);
                return;
            }
        }
       if($picUrl){
           $data = null;
           $data['taskId'] = $taskId;
           $data['progressId'] = $progressId;
           $data['customerMassage'] = 1;
           $data['content'] = $picUrl;
           $data['type'] = 'image';
           $data['createTime'] = date("Y-m-d H:i:s");
           $data['updateTime'] = date("Y-m-d H:i:s");
           $result = $taskMessage->add($data);
           if(!$result){
               Output::instance()->resultCode(code_sql_error);
               return;
           }
       }
        Output::instance()->resultCode();
    }
    //任务失败
    public function taskFail(){
        Session::switchCustomer(0);
        $taskModel = M("module_user_task");
        $where['status'] =array("IN",[1,4]);
        $time = date("Y-m-d H:i:s");
        $list = $taskModel->where($where)->field("id,startTime,configJson,taskName,cid,uid")->select();
        foreach($list as $key=>$value){
            $configJson = json_decode($value['configJson'],true);
            $taskTime = $configJson['taskTime'];
            $endTime = strtotime("$time -$taskTime hours");
            if($endTime>=strtotime($value['startTime'])){
                $data['status'] = 3;
                $data['updateTime'] = $time;
                $taskModel->where("id=".$value['id'])->save($data);
                $cid = $value['cid'];
                Session::switchCustomer($cid);
                $userName = M("user")->where("id=".$value['uid'])->getField("userName");

                $url = WeixinApi::getDomainName();
                $tempUrl = $url['SERVER_HOST']. "call.html?customerId=" . $cid .
                    "&module=productTask&method=index&params=%7B%22id%22%3A".$value['id'].",%22h%22%3A%22progressList%22%7D";
                $tempUrl = urlencode($tempUrl);
                $sendData['first'] = array('value'=> '您没有在规定的时间内完成任务','color'=>'#f80712');
                $sendData['keyword1'] = array('value'=> $value['taskName'],'color'=>'#173177');
                $sendData['keyword2'] = array('value'=> '任务超时','color'=>'#173177');
                $endTime = date("Y-m-d H:i:s",strtotime($value['startTime']." +$taskTime hours"));
                $sendData['keyword3'] = array('value'=> "您的任务应该在".$endTime."前完成",'color'=>'#173177');
                $sendData['remark'] = array('value'=>'点击进入任务' ,'color'=>'#0751f8');
                TemplateMessage::send( $userName,$cid,'taskExamine',$tempUrl,$sendData);
            }
        }

    }
    //进行数据迁移，将之前存在商品中的任务迁移到已经购买的订单详情中
    public function  dataMargain(){
        Session::switchCustomer(0);
        $orderModel = M("module_product_order_detail");
        $where['c.status'] = array("IN",['paying','delivering','delivered','notsubmit']);
        $where['b.taskModel'] = array("EQ",1);
        $orderInfo = $orderModel->alias("a")
            ->join("inner join wx_module_product b on a.pid = b.id")
            ->join("inner join wx_module_product_order c on a.oid=c.id")
            ->where($where)
            ->field("b.json,a.id")
            ->select();
        foreach ($orderInfo as $key=>$value){
            $configJson = json_decode($value['json'],true);
            $data['taskInfo'] = $configJson['taskInfo'];
            $data['taskModel'] = 1;
            $orderModel->where("id=".$value['id'])->save($data);
        }
    }
    //获得手机端URL
    public function getMobileUrl () {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $url = R('MiContent/getH5ServerHost');
        $url .= "call.html?customerId=".$customerId."&module=productTask&method=index&params=%7B%22h%22:%22index%22%7D";
        $return['code'] = 0;
        $return['msg'] = 'url返回';
        $return['data'] = $url;
        Output::instance()->object($return);

    }

    /** 任务管理菜单 */
    public function getTaskMenu(){
        // 菜单配置数组
        $data = [
            'task'    => [
                'group'     => '任务管理',
                'children'  => [
                    [
                        'name'  => '任务管理',
                        'url'   => '#/joymap/productTask/list',
                    ],
                    [
                        'name'  => '任务统计',
                        'url'   => '#/joymap/productTask/statistics',
                    ]
                ]
            ]
        ];

        $index = 1;
        $arr_child = [];
        foreach ($data['task']['children'] as $child_k => $child_v) {
            // 这个菜单是_胡英俊_给出的菜单树demo结构
            $m = [
                'id'        => $index,
                'name'      => $child_v['name'],
                'level'     => 1,
                'parent'    => 0,
                'path'      => "$index",
                'icon'      => '',
                'url'       => $child_v['url'],
                'isMenu'    => true,
                'children'  => []
            ];
            array_push($arr_child, $m);
            $index++;
        }

        $menu = [
            'id'        => 0,
            'group'     => $data['task']['group'],
            'children'  => $arr_child
        ];


        Output::instance()->object(['data' => [$menu]]);
    }
}